/*
 * Tableau Snippet
 *
 * Authors:
 *    Chris Burdick, ITema 
 *    Chad Robinson, ITema
 *
 * Version: 1.0.0
 *
 * This module is designed to build tabular output, such as to build product category pages for a Web store.
 * Currently it's not recursive, so all elements to be displayed must be in one container, with no children.
 * Recursion, lang entries for pagination controls, and control over sorting are planned for a future release.
 *
 * Make sure the page you place this on is NOT cacheable or cached! 
 *
 * Parameters:
 *   startId    - The ID of the page whose children you want to list
 *   columns    - The number of columns the table should have, defaults to 3
 *   rows       - The max. number of rows the table should have, see pagination, defaults to 3
 *   paginate   - If 1, and the table is filled to its max. rows but there is more data, outputs <First <Prev Next> Last> elements
 *   pcloc      - Where to place pagination controls, may be 'top', 'bottom', or 'both'
 *   pageNums   - If paginate is true, shows page numbers, as in <First  <Prev ...  4 5 [6] 7 8 ... Next> Last>
 *   phrefClass - Class tag to output with pagination HREF tags
 *   ppnumClass - Class tag to output with pagination page number tags
 *   tableClass - Class tag to output for the table
 *   trClass    - CLass tag to output for each row
 *   tdClass    - Class tag to output for each cell
 *   alttrClass - Class tag to output for alternate rows, defaults to trClass
 *   alttdClass - Class tag to output for alternate columns, defaults to tdClass
 *   tmpl       - Chunk used to render each table cell
 *
 * Example usage:
 *  [[Tableau? &startId=`47` &columns=`3` &rows=`4` &paginate=`1` &pagenums=`1` &tmpl=`ProductSummary`]]
 *
 */

$Tableau['startId']     = (isset($startId))     ? $startId : 0;
$Tableau['columns']     = (isset($columns))     ? $columns : 3;
$Tableau['rows']        = (isset($rows))        ? $rows : 3;
$Tableau['paginate']    = (isset($pagination))  ? $pagination : 1;
$Tableau['pcloc']       = (isset($pcloc))       ? $pcloc : 'both';
$Tableau['pageNums']    = (isset($pageNums))    ? $pageNums : 1;
$Tableau['phrefClass']  = (isset($phrefClass))  ? $phrefClass : 'Tableau-phref';
$Tableau['ppnumClass']  = (isset($ppnumClass))  ? $ppnumClass : 'Tableau-ppnum';
$Tableau['trClass']     = (isset($trClass))     ? $trClass : 'Tableau-tr';
$Tableau['tdClass']     = (isset($tdClass))     ? $tdClass : 'Tableau-td';
$Tableau['tableClass']  = (isset($tableClass))  ? $tableClass : 'Tableau-table';
$Tableau['alttdClass']  = (isset($alttdClass))  ? $alttdClass : $Tableau['tdClass'];
$Tableau['alttrClass']  = (isset($alttrClass))  ? $alttrClass : $Tableau['trClass'];
$Tableau['tmpl']        = (isset($tmpl))        ? $tmpl : 'Tableau-tpl';

// TODO: Support sorting options
// TODO: Support child recursion
// TODO: Support filtering by TV values.
$result = $modx->db->select('`id`,`pagetitle`,`description`', $modx->db->config['table_prefix'] . 'site_content',
							' parent=' . $Tableau['startId'] . ' AND deleted=0 and published=1');
$rowcount = $modx->db->getRecordCount($result);
$rows = $modx->db->makeArray($result);

// Be careful to avoid tampering
$startrow = intval($_GET['startrow']);
if (!isset($_GET['startrow']) || $startrow < 0 || $startrow > $rows) {
	$startrow = 0;
}

$Tableau['perpage'] = $Tableau['rows'] * $Tableau['columns'];
$Tableau['perpage'] = $Tableau['perpage'] > 0 ? $Tableau['perpage'] : 1;
$Tableau['pagenum'] = intval($startrow / $Tableau['perpage']) + 1;
$Tableau['pagecount'] = intval($rowcount / $Tableau['perpage']) + 1;

if (!function_exists('TableauPControls')) {
	function TableauPControls($Tableau, $rowcount, $startrow) {
		global $modx;
		
		if ($Tableau['rowcount'] < $Tableau['$perpage']) return;

		// We use a table instead of a DIV here so we can make sure things line up.
		// This way, if the designer sets a width such as 80% on the output table
		// we'll get the same width here, and the pagination controls will left/right
		// align properly. The controls themselves are DIVs, so the designer can
		// float them or do whatever else s/he wants.
		
		// TODO: Use a different class for each control element to allow the designer
		// to left/center/right controls as they see fit.
		echo '<table class="' . $Tableau['tableClass'] . '"><tr><td>' . "\n";
		// First
		$url = $modx->makeUrl($modx->documentIdentifier, '', '');
		echo '<div class="' . $Tableau['phrefClass'] . '"><a href="' . $url . '">First</a></div>';
		
		// Prev
		$prow = $startrow - $Tableau['perpage'];
		if ($prow < 1) $prow = 1;
		$url = $modx->makeUrl($modx->documentIdentifier, '', '&startrow=' . $prow);
		echo '<div class="' . $Tableau['phrefClass'] . '"><a href="' . $url . '">Previous</a></div>';
		
		// Page numbers
		// TODO: Later we want page number styles, like to do    4 5 [6] 7 8
		// For now we just output Page 4 / 7
		echo '<div class="' . $Tableau['ppnumClass'] . '">Page ' . $Tableau['pagenum'] . ' of ' . $Tableau['pagecount'] . '</div>';	

		if ($Tableau['pagenum'] < $Tableau['pagecount']) {
			// Next
			$nrow = $startrow + $Tableau['perpage'];
			$url = $modx->makeUrl($modx->documentIdentifier, '', '&startrow=' . $nrow);
			echo '<div class="' . $Tableau['phrefClass'] . '"><a href="' . $url . '">Next</a></div>';
		
			// Last
			$lastpage = ($Tableau['pagecount']-1) * $Tableau['perpage'] + 1;
			$url = $modx->makeUrl($modx->documentIdentifier, '', '&startrow='. $lastpage);
			echo '<div class="' . $Tableau['phrefClass'] . '"><a href="' . $url . '">Last</a></div>';
		}
		echo '</tr></td></table>' . "\n";
	}
}

// Get cell template, and identify its placeholders
$tmpl = $modx->getChunk($Tableau['tmpl']);
$matches = array ();
preg_match_all('~\[\+(.*?)\+\]~', $tpl, $matches);
$sizeofmatches = sizeof($matches);

for ($j=0; $j < sizeof($matches); $j++){
	$ezmatch["$matches[1][$j]"];
}

if ($Tableau['rows'] < sizeof($rows)){
   if ($Tableau['pcloc'] != 'bottom') TableauPControls($Tableau, $rowcount, $startrow);
}

echo '<table class="' . $Tableau['tableClass'] . '">' . "\n";
for ($rowopen = $col = $row = $i = 0; $i + $startrow < $rowcount && $row < $Tableau['rows']; $i++) {
	if ($col == 0) {
		$rowclass = ($row % 2 == 0) ? $Tableau['trClass'] : $Tableau['alttrClass'];
		echo '<tr class="' . $rowclass . '">';
		$rowopen = 1;
	}

	$colclass = ($col % 2 == 0) ? $Tableau['tdClass'] : $Tableau['alttdClass'];
	echo '<td class="' . $colclass . '">';

	// Fill in template placeholders
	$cont = $tmpl;
	foreach($rows[$i+$startrow] as $k => $val) {
		$cont = str_replace('[+' . $k . '+]', $val, $cont);
	}
    echo $cont;

// PUT CONTENT IN TR's
   //echo "\t\t\t" . 'ID: ' . $row['id'] . "\n"; //'     PAGETITLE: ' . $row['pagetitle'] . '     DESCRIPTION: ' . $row['description'] 

	echo '</td>';
	
	$col++;
	if ($col == $Tableau['columns']) {
		$col = 0;
		echo '</tr>' . "\n";
		$rowopen = 0;
		$row++;
	}
}
if ($rowopen) echo '</tr>' . "\n";
echo '</table><br/>' . "\n";

// Pagination controls
if ($Tableau['rows'] < sizeof($rows)){
   if ($Tableau['pcloc'] != 'top') TableauPControls($Tableau, $rowcount, $startrow);
}
